package com.examples.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.annotation.processing.FilerException;

public class FileSample {

	public List<String> readFromFile(String filename) {
		ArrayList<String> str = new ArrayList<String>();
		

		try {

			FileReader filein = new FileReader(filename);
			BufferedReader obj = new BufferedReader(filein);

			int i = 0;
			String str1;
			while ((str1 = obj.readLine()) != null) {
				str.add(str1);
			}
			obj.close();
			filein.close();
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}

		return str;
	}

	public void writeToFile(List<String> buff, String filename) {

		String str1;

		try {

			FileWriter fileout = new FileWriter(filename);
			BufferedWriter obj = new BufferedWriter(fileout);

			System.out.println("\n\nWritting");
			int i = 0;

			while (i < buff.size()) {
					obj.write(buff.get(i++));
					obj.newLine();
				} 
		
			obj.close();
			fileout.close();
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}

	}

	public List<String> findGamilId(List<String> buff) {
		List<String> res = new ArrayList<String>();

		for (int i = 0; i < buff.size();  i++) {

			if (buff.get(i).contains("gmail.com") == true) {
				res.add(buff.get(i));
			} 
			
		}
		return res;
	}

	public static void main(String[] args) {
		// reverse a string
		// read from file
		FileSample objf = new FileSample();
		List<String> buff = objf.readFromFile("inputEmailID.txt");
		System.out.println("Read Id's\n");
		System.out.println(buff);

		// find gmail ids
		List<String> res = objf.findGamilId(buff);
		System.out.println("\n\nFiltered Id,");
		System.out.println(res);
		Collections.sort(res);
		// write to file
		
		objf.writeToFile(res, "outputemailID.txt");
		System.out.println(res);
		System.out.println("Done");
	}
}
